#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QProcess>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    process(nullptr)
{
    ui->setupUi(this);
    connect(ui->searchButton, &QPushButton::clicked, this, &MainWindow::onSearchButton);
    process = new QProcess(this);
    connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &MainWindow::showResult);
    connect(process, &QProcess::readyReadStandardOutput, this, &MainWindow::onReadResult);
    connect(process, &QProcess::readyReadStandardError, this, &MainWindow::onReadError);
}

void MainWindow::onSearchButton()
{
    qDebug() << "User clicked on the button!";
    ui->searchResult->clear();
    ui->errorResult->clear();
//    if (process)
//    {
//        delete process;
//    }

    QString agFile = "/usr/local/bin/ag";
//    QStringList arguments;
//    arguments.append("-C");
//    arguments.append("--filename");
////    arguments.append("-H");
//    arguments.append("BTREE");
//    // must use absoulte dir below
//    arguments.append("/Users/choice/code/CopyQ");
////    arguments.append(">temp.txt");
////    arguments.append("~/code/c");

    QString exeFile = "/usr/local/opt/coreutils/libexec/gnubin/cat";
    QStringList arguments;
    arguments.append("/Users/choice/test_qt.txt");

    process->setStandardOutputFile("/Users/choice/test_cat.txt");

    process->start(exeFile, arguments);
}

void MainWindow::showResult(int exitCode, QProcess::ExitStatus exitStatus)
{
    qDebug() << exitCode << " " << exitStatus;
    qDebug() << "process finished!";
}

void MainWindow::onReadResult()
{
    qDebug() << "process onReadResult!";
    auto output = process->readAllStandardOutput();
    auto result = QString::fromUtf8(output);
    qDebug() << result;
    ui->searchResult->appendPlainText(result);
}

void MainWindow::onReadError()
{
    auto error = process->readAllStandardError();
    auto result = QString::fromUtf8(error);
    qDebug() << result;
    ui->errorResult->appendPlainText(result);
}

MainWindow::~MainWindow()
{
    if (process)
    {
        delete process;
    }
    delete ui;
}
